<?php

namespace App\Observers;
use App\Models\Fang;
use Elasticsearch\ClientBuilder;
use GuzzleHttp\Client;
class FangObserver
{
    //添加房源数据入库之前
    public function creating(Fang $fang){
        if(request()->get('fang_config')){
            //对于配套设施数组转为字符串操作
            $fang->fang_config=implode(',',request()->get('fang_config'));
            //得到请求逆向转换的url地址
            $url=config('geo.url');
            $address=request()->get('fang_addr');
            $city=request()->get('fang_city');
            //把字符串中的%s进行替换
            $url=sprintf($url,$address,$city);
            //发起请求
            $client=new Client(['timeout'=>5,'verify'=>false]);
            $response=$client->get($url);
            $json=(string)$response->getBody();
            //转为经纬度
            $arr=json_decode($json,true);
            $location=count($arr['geocodes'])>0?$arr['geocodes'][0]['location']:'0,0';
            $arr=explode(',',$location);
            $fang->longitude=$arr[0];
            $fang->latitude=$arr[1];
        }
    }
    //添加房源数据入库之后
    public function created(Fang $fang){
        //此数据是es中定义字段所添加文档要有的数据
        $id=$fang->id;
        $name=$fang->fang_name;
        $desn=$fang->fang_desn;
        if(request()->get('fang_config')){
            $hosts=config('es.host');
            $client=ClientBuilder::create()->setHosts($hosts)->build();
            //谢文档
            $params=[
                'index'=>'zfw',
                'id'=>$id,
                'body'=>[
                    'name'=>$name,
                    'desn'=>$desn
                ]
            ];
            //文档写入索引
            $client->index($params);
        }
    }
    //更新数据入库之前
    public function updating(Fang $fang){
        //配套设施字符串拼接和经纬度逆向转换
        $this->creating($fang);
        //es更新文档到es索引中
        $this->created($fang);
    }
}
